package com.xuecheng.framework.utils;

import org.apache.commons.io.FileUtils;

import java.io.*;
import java.util.*;

/**
 * 视频分割成m3u8工具类
 */
public class M3U8VideoUtil extends VideoUtil {
    public M3U8VideoUtil(String ffmpeg_path) {
        super(ffmpeg_path);
    }

    public static void setFFmpegPath(String ffmpegPath) {
        ffmpeg_path = ffmpegPath;
    }

    /**
     * 将一个mp4文件分割成m3u8
     * <p>
     * C:\测试视频\斗罗大陆-测试\斗罗大陆-第1集\斗罗大陆-第1集.mp4
     *
     * @param filePath 视频文件的路径  C:\测试视频\斗罗大陆-测试\斗罗大陆-第1集
     * @param fileName 视频文件名  斗罗大陆-第1集.mp4
     * @param md5      文件MD5值,m3u8文件名使用文件md5做前缀
     * @return 处理好的m3u8文件名集合
     */
    public static List<File> generateM3U8(String filePath, String fileName, String md5) {
        ProcessBuilder processBuilder = new ProcessBuilder();
        List<String> commandList = new ArrayList<>();
        commandList.add(ffmpeg_path);
        commandList.add("-i");
        commandList.add(filePath + "\\" + fileName);
        commandList.add("-y");
        commandList.add("-vcodec");
        commandList.add("copy");
        commandList.add("-acodec");
        commandList.add("copy");
        commandList.add("-hls_time");
        commandList.add("10");
        commandList.add("-hls_list_size");
        commandList.add("0");
        commandList.add(filePath+"/"+""+md5+".m3u8");
        processBuilder.command(commandList);
        processBuilder.redirectErrorStream(true);
        String result = null;
        // 执行指令
        try {
            Process process = processBuilder.start();
            result = waitFor(process);
            List<File> m3u8List = new ArrayList<>();
            File m3u8Path = new File(filePath);
            File[] listFiles = m3u8Path.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    return !name.equals(fileName) && !name.endsWith(".m3u8") && !name.endsWith(".mp4");
                }
            });
            assert listFiles != null;
            m3u8List = Arrays.asList(listFiles);
            Collections.sort(m3u8List, new Comparator<File>() {
                @Override
                public int compare(File o1, File o2) {
                    String o1Name = o1.getName().replace(md5, "").replace(".ts","");
                    String o2Name = o2.getName().replace(md5, "").replace(".ts","");
                    return Integer.parseInt(o1Name) -Integer.parseInt(o2Name);
                }
            });
            return m3u8List;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        M3U8VideoUtil.setFFmpegPath("C:\\Users\\18723\\Desktop\\xuecheng\\ffmpeg-20200401-afa5e38-win64-static\\bin\\ffmpeg.exe");
        M3U8VideoUtil.generateM3U8("C:\\Users\\18723\\Desktop\\xuecheng\\测试视频\\白蛇缘起\\白蛇缘起","白蛇缘起.mp4","a642603e33770f899bd891569a9171b2");
    }
}
